import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes } from '@/types/data'
import { Profile } from '@/types/user'
import { getProfile, removeProfile, setProfile } from '@/utils/storage'
import useStore from '..'

export default defineStore('user', {
  state() {
    return {
      profile: getProfile() as Profile
    }
  },
  actions: {
    async login(data: { account: string, password: string }) {
      const res = await request.post<ApiRes<Profile>>('/login', data)
      // console.log(res.data.result)
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    async sendSms(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    async mobileLogin(data: { mobile: string, code: string }) {
      const res = await request.post<ApiRes<Profile>>('/login/code', data)
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    logout() {
      // 清除 pinia 的数据
      this.profile = {} as Profile
      // 清除 localStorage 的信息
      removeProfile()
      // 清除购物车数据
      const { cart } = useStore()
      cart.clearCart()
    },
    async qqLogin(data: { unionId: string, source: number }) {
      const res = await request.post<ApiRes<Profile>>('/login/social', data)
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    async bindQQSms(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    async bindQQ(data: { unionId: string, mobile: string, code: string }) {
      const res = await request.post<ApiRes<Profile>>('/login/social/bind', data)
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile
        }
      })
    },
    
    async qqPatchLogin(data: any) {
      const res = await request.post<ApiRes<Profile>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    }
  }
})